package simpledb.server.drivers;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import simpledb.index.*;
import simpledb.index.hash.LinearIndex;
import simpledb.index.query.IndexSelectScan;
import simpledb.query.*;
import simpledb.record.*;
import simpledb.server.SimpleDB;
import simpledb.tx.Transaction;

public class HashTest {
    private static Schema idxsch = new Schema();
    private static Transaction tx;
    
    private static Properties config = new Properties();

    public static void main(String args[]) {
    	try {
//    		cleanDB();
    		
    		config.load(new FileInputStream("./config/indexConfig.cfg"));
			linearHashTest();
		} catch (FileNotFoundException e) {
			System.out.println("Config File: indexConfig.cfg Not Found");
			System.out.println("Exiting ... ");
		} catch (IOException e) {
			System.out.println("Error Reading Config File: indexConfig.cfg");
			System.out.println("Exiting ... ");
		}
        
    }

    public static void linearHashTest() {
        SimpleDB.init("studentdb");
        System.out.println("\n\n\tBUILD LINEAR HASH INDEX\n");
        tx = new Transaction();
  
        // Defines the schema for an index record for Col2 of the messy table
        idxsch.addStringField("dataval", 64);
        idxsch.addIntField("block");
        idxsch.addIntField("id");
        
        // Builds a Linear Hash Index on Col2 of the messy table
        Integer numBuckets = Integer.parseInt(config.getProperty("numBuckets", "100"));
        Integer ec = Integer.parseInt(config.getProperty("expandConstant","100"));
        String idxfile = config.getProperty("indexFileName");
        Index idx = new LinearIndex("linearHashIdxTest", idxsch, tx, idxfile, ec);
        ((LinearIndex)idx).setINIT_NUM_BUCKETS(numBuckets);
        Plan p = new TablePlan("messy", tx);
        UpdateScan s = (UpdateScan) p.open();
        
        
        while (s.next()) {
            idx.insert(s.getVal("col2"), s.getRid());
        }
        
        // Printing the details of all buckets post insertion.
        
        System.out.println("\n#############  FINAL VIEW OF THE INDEX FILE #############");
        ((LinearIndex)idx).printAllBuckets();
        System.out.println("\n#############  FINAL VIEW OF THE INDEX FILE #############");	
        s.close();
        idx.close();
        tx.rollback();
     
    }
    
    public static void cleanDB() {
    	try {
			Process p = Runtime.getRuntime().exec("C:\\Users\\zenwalker\\studentdb\\cleanDB.bat");;
			p.waitFor();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    private static void testIndexSelect() {
        Index idx = new LinearIndex("hashIdx", idxsch, tx);
        Plan p = new TablePlan("student", tx);
        TableScan s1 = (TableScan) p.open();
        String srchString = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa110";
        Constant searchkey = new StringConstant(srchString);
        Scan s2 = new IndexSelectScan(idx, searchkey, s1);
        ArrayList<Constant> vals = new ArrayList<Constant>();
        while (s2.next())
           vals.add(s2.getVal("sid"));
        s2.close();  // also closes s1 and idx
        int count = 0;
        Scan s3 = p.open();
        while (s3.next()) 
           if (s3.getVal("majorid").equals(searchkey)) {
              count++;
              if (!vals.contains(s3.getVal("sid")))
                 System.out.println("*****HashTest: bad index select");
           }
        s3.close();
        if (count != vals.size())
           System.out.println("*****HashTest: bad index select count");
     }

}
